package com.ifcar.app.activity;

import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.bean.VoteBean;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.rss.GetContent;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.activity.R;

public class VoteSubmit extends BaseActivity {
	private VoteBean vb;
	
	private TextView vote_question;
	private TextView user_attitude;
	private TextView already_num;
	
	private LinearLayout vote_item_list_lay;
	
	private Button vote_submit;
	private Button vote_cancel;
	private Button vote_exit;
	
	private int percentLength = 0;
	
	
	private int flag;
	
	private RadioButton radios[];
	private List<Map<String, Object>> itemList;
	private String voteId ;
	private String itemId;
	private ProgressDialog p;
	
	private Animation bottomin;
	private Animation vote_see;
	private TextView addone;
	private int voteNum;
	private ThemeSettingsHelper themeSettingsHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.vote_submit_content);
		themeSettingsHelper = getThemeSettingsHelper();
		bottomin = AnimationUtils.loadAnimation(this, R.anim.vote_do);
		vote_see = AnimationUtils.loadAnimation(this, R.anim.vote_see);
		
		Bundle b = getIntent().getBundleExtra("vb");
		vb = (VoteBean)b.getSerializable("votebean");
		flag = b.getInt(StringUtil.ALREADY_VOTE);
		
		itemList = vb.getItemLsit();
		
		
		ContentValues values = new ContentValues();					
		values.put(NewsSQLiteOpenHelper.VOTE_ID, vb.getId());
		Cursor cur = db.query(NewsSQLiteOpenHelper.VOTE_TABLE, new String[]{NewsSQLiteOpenHelper.VOTE_ID},
				NewsSQLiteOpenHelper.VOTE_ID + "=" + vb.getId(), null, null, null, NewsSQLiteOpenHelper.VOTE_AUTO_ID + " desc");

		voteNum = cur.getCount();
		cur.close();
		
		initViews();
		vote_question.setText(vb.getItemQuestion());
		
		if(flag==1){
			updateView();
		}else{
			user_attitude.setText(getResources().getString(R.string.user_attitude));
			already_num.setText("" + vb.getAllVoteNum());
			
			radios = new RadioButton[itemList.size()];
			LayoutInflater flater = getLayoutInflater();
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
			Map<String,Object> m ;
			for(int i=0;i<itemList.size();i++){
				m = itemList.get(i);
				View vi = flater.inflate(R.layout.vote_with_tab_submit_item, null);
				RadioButton rb = (RadioButton)vi.findViewById(R.id.vote_item_radio);
				radios[i] = rb;
				radios[i].setTag(StringUtil.GetString(m.get((StringUtil.VOTE_ITEM_ID))));
				radios[i].setOnClickListener(checkVoteItemClickListener);

				TextView text1 = (TextView)vi.findViewById(R.id.vote_item_number);
				text1.setText((i+1)+". ");
				
				TextView text2 = (TextView)vi.findViewById(R.id.vote_item_text);
				text2.setText(StringUtil.GetString(m.get(StringUtil.VOTE_ITEM_NAME)));
				vote_item_list_lay.addView(vi,params);
			}
		}
		
		
		vote_submit.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				voteId = vb.getId();				
				int sum=0;
				for(int i=0;i<radios.length;i++){
					if(radios[i].isChecked())
						itemId = radios[i].getTag().toString();
					else
						sum++;
				}
				
				if(sum==radios.length){
					AlertDialog.Builder builder = new AlertDialog.Builder(VoteSubmit.this);
					builder.setIcon(android.R.drawable.ic_dialog_alert)
						.setTitle("请选择")
						.setMessage(R.string.no_item_selectd)
						.setCancelable(true)
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which){}}).show();
				}else{
					p = new ProgressDialog(VoteSubmit.this);
					p.setMessage("提交投票数据...");
					p.setCancelable(true);
					p.setOnCancelListener(new DialogInterface.OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface arg0) {
							// TODO Auto-generated method stub
							if(null!=p){
								p.dismiss();
							}
							
						}
					});
					p.show();
					
					new Thread(){
						@Override
						public void run() {
							MyApplication appdata = (MyApplication) VoteSubmit.this.getApplicationContext();
							
							String res = GetContent.doVote(voteId, itemId,VoteSubmit.this); //　投票成功
							try {
								if(res!=null){
									JSONObject obj = new JSONObject(res);
									if(obj!=null){
										String r = obj.getString("result");
										if("success".equals(r)){
											//  保存数据库
										
											ContentValues values = new ContentValues();					
											values.put(NewsSQLiteOpenHelper.VOTE_ID, vb.getId());
											db.insert(NewsSQLiteOpenHelper.VOTE_TABLE, null, values);
										
											
											appdata.setVoteId(voteId);
											handler.sendEmptyMessage(0);
											
										}else{
											appdata.setVoteId(null);
											handler.sendEmptyMessage(1);
										}
									}
								}else {
									appdata.setVoteId(null);
									handler.sendEmptyMessage(1);
								}
							} catch (JSONException e) {
								appdata.setVoteId(null);
								handler.sendEmptyMessage(1);
								e.printStackTrace();
							}						
						}
					}.start();
					
				}
			}
		});

		vote_exit.setOnClickListener(clickListener);		
		vote_cancel.setOnClickListener(clickListener);
	}
	
	private Button.OnClickListener clickListener = new Button.OnClickListener() {			
		@Override
		public void onClick(View v) {
			VoteSubmit.this.finish();
		}
	};
	
	private Handler handler = new Handler(){
		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case 0:
				
				p.cancel();
				Toast t= Toast.makeText(VoteSubmit.this, "投票成功！", Toast.LENGTH_SHORT);
				t.setGravity(Gravity.CENTER_HORIZONTAL, 0, 200);
				t.show();
				is_success = true;
				isDo = true;
				/**
				 * 显示投票结果
				 */
				updateView();
				break;
			case 1:
				p.cancel();
				Toast t1 = Toast.makeText(VoteSubmit.this, "对不起，投票失败！", Toast.LENGTH_SHORT);
				t1.setGravity(Gravity.CENTER_HORIZONTAL, 0, 200);
				t1.show();
				is_success = false;
				/**
				 * 显示投票结果
				 */
				updateView();
				break;
			}
		}
	};
	
	/**
	 * 显示投票结果
	 */
	TextView voteItems[];
	private boolean is_success = false;
	private boolean isDo = false;
	protected void updateView() {
		vote_submit.setVisibility(View.GONE);
		vote_cancel.setVisibility(View.GONE);
		vote_exit.setVisibility(View.VISIBLE);
		
		if(isDo || voteNum == 1){
			user_attitude.setText(getResources().getString(R.string.vote_already));
			isDo = false;
		} else 
			user_attitude.setText(getResources().getString(R.string.vote_missing));
		
		already_num.setText((vb.getAllVoteNum() + 1)+"");
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		
		vote_item_list_lay.removeAllViews();
		
		LayoutInflater flater = getLayoutInflater();
	
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int s = metrics.widthPixels;
		percentLength = (int)(s * 0.70);
		
		voteItems = new TextView[itemList.size()];
		
		int sum = 0;
		for(int i=0;i<itemList.size();i++){
			View itemSee = flater.inflate(R.layout.vote_with_tab_item_see, null);
			themeSettingsHelper.setViewBackgroudColor(VoteSubmit.this, itemSee, R.color.main_bg_color);
			int itemNum = Integer.parseInt(StringUtil.GetString(itemList.get(i).get(StringUtil.VOTE_ITEM_NUM)));
			float percent = StringUtil.getPercent(itemNum, vb.getAllVoteNum());
			
			TextView titleNum = (TextView)itemSee.findViewById(R.id.vote_item_see_number);
			titleNum.setText((i + 1) + ". ");
			
			TextView textTitle = (TextView)itemSee.findViewById(R.id.vote_item_see_text);
			textTitle.setText(StringUtil.GetString(itemList.get(i).get(StringUtil.VOTE_ITEM_NAME)));
			if(flag != 1)
				if(radios[i].isChecked()){ // 显示加 1 
					if(is_success){ // 投票成功
						addone = (TextView)itemSee.findViewById(R.id.vote_item_see_add_one);
						addone.startAnimation(bottomin);
					}
				}
			
			voteItems[i] = (TextView)itemSee.findViewById(R.id.vote_item_progress);
			voteItems[i].setWidth((int)(percent*percentLength));
			voteItems[i].setHeight(10);
			voteItems[i].setBackgroundDrawable(getBGDrawable(i));
			voteItems[i].startAnimation(vote_see);
			
			TextView textPercent = (TextView)itemSee.findViewById(R.id.vote_item_pencent);
			int temp = (int)(percent*100);
			sum+=temp;
			if(i==itemList.size()-1)
				temp = 100-sum+temp;
			textPercent.setText(temp + "%");
			
			vote_item_list_lay.addView(itemSee, params);
		}
		
		bottomin.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
				addone.setVisibility(View.INVISIBLE);
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			@Override
			public void onAnimationStart(Animation animation) {
				addone.setVisibility(View.VISIBLE);
			}
		});
		
		vote_see.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			@Override
			public void onAnimationStart(Animation animation) {
				for(int i=0;i<voteItems.length;i++)
					voteItems[i].setVisibility(View.VISIBLE);
			}
		});
	}

	private Drawable getBGDrawable(int i) {
		Drawable d = null;
		switch (i) {
		case 0:
			d = getResources().getDrawable(R.drawable.vote_bule);
			break;
		case 1:
			d = getResources().getDrawable(R.drawable.vote_green);
			break;
		case 2:
			d = getResources().getDrawable(R.drawable.vote_red);
			break;
		case 3:
			d = getResources().getDrawable(R.drawable.vote_yellow);
			break;
		}
		return d;
	}

	private RadioButton.OnClickListener checkVoteItemClickListener =  new RadioButton.OnClickListener(){
		public void onClick(View arg0) {
			for(int i=0;i<radios.length;i++){
				if(arg0==radios[i]){
					radios[i].setChecked(true);
				}else{
					radios[i].setChecked(false);
				}
			}
		};
	};
	
	/**
	 * 初始化组建
	 */
	private void initViews() {
		vote_question = (TextView)findViewById(R.id.vote_question);
		user_attitude = (TextView)findViewById(R.id.do_vote_user_attitude);
		already_num = (TextView)findViewById(R.id.do_vote_sum_num);
		
		vote_item_list_lay = (LinearLayout)findViewById(R.id.vote_item_list_layout);
		
		vote_submit = (Button)findViewById(R.id.do_submit_button);
		vote_cancel = (Button)findViewById(R.id.do_cancel_button);
		vote_exit = (Button)findViewById(R.id.do_exit_button);
	}
	
	public void onApplyTheme() {
        super.onApplyTheme();
        themeSettingsHelper.setViewBackgroudColor(this, R.id.vote_submit_layout, R.color.main_bg_color);
        themeSettingsHelper.setViewBackgroud(this, R.id.do_submit_button, R.drawable.netease_small_button);
        themeSettingsHelper.setViewBackgroud(this, R.id.do_cancel_button, R.drawable.netease_small_button);
        themeSettingsHelper.setViewBackgroud(this, R.id.do_exit_button, R.drawable.netease_small_button);
        themeSettingsHelper.setTextViewColor(this, R.id.do_submit_button, R.color.list_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.do_cancel_button, R.color.list_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.do_exit_button, R.color.list_title_color);
        themeSettingsHelper.setTextViewColor(this, vote_question, R.color.vote_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.vote_question_text_f, R.color.vote_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.do_vote_user_attitude, R.color.vote_desc_color);
        themeSettingsHelper.setTextViewColor(this, R.id.do_vote_sum_num_f, R.color.vote_desc_color);
	}
	
}
